package com.bizmda.bizsip.sample.applog.listener;

import cn.hutool.json.JSONObject;
import com.bizmda.bizsip.common.BizConstant;
import com.bizmda.bizsip.common.BizMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * RabbitMQ接收服务
 * @author shizhengye
 */
@Slf4j
@Service
public class AppLogQueueListener {
    public static final String APP_LOG_QUEUE = "queue.bizsip.applog";
    private static final String[] APP_LOG_TYPE={"0-App服务成功 ","1-App服务失败 ","2-App服务挂起 ","3-Sink服务成功","4-Sink服务失败"};
    private final Jackson2JsonMessageConverter jackson2JsonMessageConverter =new Jackson2JsonMessageConverter();

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = APP_LOG_QUEUE, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = BizConstant.BIZSIP_LOG_EXCHANGE),
            key = BizConstant.BIZSIP_LOG_ROUTING_KEY))
    public void onMessage(Message message) {
        try {
            this.process(message);
        }
        catch (Exception e) {
            log.error("App服务日志侦听器出错!",e);
        }
    }

    private void process(Message message) {
        Map<String,Object> map = (Map<String,Object>)jackson2JsonMessageConverter.fromMessage(message);
        int type = (int)map.get("type");
        BizMessage<JSONObject> inBizMessage = new BizMessage<>((Map<String, Object>) map.get("request"));
        BizMessage<JSONObject> outBizMessage = new BizMessage<>((Map<String, Object>) map.get("response"));
        log.info("\n{} App服务ID:{} 返回码:{}-{} 平台流水号:{}\n请求报文:{}\n响应报文:{}",
                APP_LOG_TYPE[type],inBizMessage.getAppServiceId(),
                outBizMessage.getCode(),outBizMessage.getMessage(),inBizMessage.getTraceId(),
                inBizMessage.getData(),outBizMessage.getData());
    }
}
